<?php

class ctrl_wish_dxmOrder extends L {

    private static $es = false;
    /**
     * 描述 ：店小秘订单页面展示
     * 作者 ：Zoro.Zhu
    **/
    public function index(){
        $this->view->_pagingHtml = $this->paging();
        $this->view->headTitle = '店小秘订单';
        $this->view->dxmAccount = model_com::getDxmAccount();
        $this->view->trackDogStatus = model_com::getVsConfig('trackDogStatus');
        $this->display('/html/wish/dxmOrder.html');
    }

    /**
     * 描述 : 获取分页
     * 作者 : Zoro.Zhu
     */
    public function &paging($params = array()){
        if (self::$es) {
            $sql = model_dxmOrder::searchSqlEs($params);
        } else {
            $sql = model_dxmOrder::searchSql($params);
        }
        $config = array(
            "<div><input type=\"checkbox\" name=\"checkAll\"></div>" => '<input type="checkbox" name="check[]"  value="{`orderId`}">',
            '订单信息' => array(
                '_attr' => array(
                    'body' => '<div class="multiline">
                          <p>店小秘订单号：{`orderId`}</p>
                          <p>包裹号：{`parcelNum`}</p>
                          <p>平台：{`platform`}</p>
                          <p>店小秘账号：{`dxmAccount`}</p>
                          <p>销售店铺：{`pAccount`}</p>
                          <p>订单状态：{`orderState`}</p>
                          <p>最后更新时间：{`updTime`}</p>
                          <p>付款时间：{`paymentTime`}</p>
                          <p>标记发货时间：{`shipTime`}</p>
                     </div>',
                    'attr' => 'style="width: 15%;"',
                )
            ),
            '产品信息' => array(
                '_attr' => array(
                    'body' => '{`_productInfo`}',
                    'attr' => 'style="width: 20%;"',
                )
            ),
            '收件信息' => array(
                '_attr' => array(
                    'body' => '<div class="multiline">
                          <p>国家：{`countryEn`}({`country`})</p>
                          <p>收件人：{`contact`}</p>
                          <p>地址1：{`address1`}</p>
                          <p>地址2：{`address2`}</p>
                          <p>城市：{`city`}</p>
                          <p>州省：{`province`}</p>
                          <p>邮编：{`zip`}</p>
                          <p>电话：{`phone`}</p>
                     </div>',
                    'attr' => 'style="width: 14%;"',
                )
            ),
            '物流信息' => array(
                '_attr' => array(
                    'body' => '<div class="multiline">
                          <p>物流渠道：{`logistics`}</p>
                          <p>跟踪号：<a onclick="dxmOrderObj.getLogisticsInfo(\'{`trackNo`}\')">{`trackNo`}</a></p>
                          <p>物流商称重(KG)：{`pricing_weight`}</p>
                          <p>物流运费：{`shipFee`}</p>
                          <p>打印面单时间：{`printTime`}</p>
                          <p>上网时间：{`onlineTime`}</p>
                          <p>物流最后时间：{`lastTime`}</p>
                          <p>物流状态：{`trackDogStatus`}</p>
                          <p>发货天数：{`shippingDay`}</p>
                     </div>',
                    'attr' => 'style="width: 19%;"',
                )
            ),
            '采购信息' => array(
                '_attr' => array(
                    'body' => '<div class="multiline">
                          <p>1688订单号：{`pickingRemark`}</p>
                          <p>快递单号：<a onclick="dxmOrderObj.getSingleExpress(\'{`singleExpress`}\')">{`singleExpress`}</a></p>
                          <p>采购总成本：{`costPriceTotal`}</p>
                          <p>产品成本：{`cost`}</p>
                          <p>快递费：{`shippingFee`}</p>
                          <p>订单备注：<font color="red">{`orderRemark`}</font></p>
                     </div>',
                    'attr' => 'style="width: 12%"',
                )
            ),
            '利润情况' => array(
                '_attr' => array(
                    'body' => '<div class="multiline">
                          <p>售价：{`currencyShop`} {`priceTotal`} ({`rmbPriceTotal`})</p>
                          <p>平台佣金：{`currencyShop`} {`platPrice`} ({`rmbPlatPrice`})</p>
                          <p>采购总成本：{`costPrice`}</p>
                          <p>物流运费：{`shipFee`}</p>
                          <p style="color: #FF0000">退款金额：{`refundCurrency`} {`refundPrice`} ({`rmbRefundPrice`})</p>
                          <p>毛利：{`gross`}</p>
                          <p>毛利率：{`grossMargin`}</p>
                          <p>成本利润率：{`costMargin`}</p>
                     </div>',
                    'attr' => 'style="width: 15%"',
                )
            ),
            '操作' => '<input class="btn btn-danger" onclick="dxmOrderObj.updPrice(\'{`orderId`}\');" type="button" value="修改"><br>
                    <a target="_blank" class="btn btn-warning" onclick="dxmOrderObj.printOk(\'{`dxmAccount`}\',\'{`orderId`}\',\'{`logisticsId`}\',\'{`parcelNum`}\')">打印</a>',
            '_attr' => array(
                "attr" => array (
                    "table" => 'id=dxmOrderList class="table table-hover table-condensed table-striped table-scroll jsHoverDetails textC"',
                    "btr" => "align='center' class='of-paging_item_odd tr_{`orderId`}'",
                ),
                'data' => &$sql,
                'params' => &$params,
                'call' => array($this, 'asCall'),
                'method' => __METHOD__,
                'save' => 'auto',
                'empty' => '查无此数据',
                'db' => self::$es ? 'es' : '',
            )
        );
        return $this->_com->paging($config);
    }

    /**
     * 描述 : 整理数据
     * 作者 : Zoro.Zhu
     */
    public function asCall(&$data){
        if(!empty($data['data'][0]) && !isset($data['data'][0]['orderData'])){
            $orderIdAy = [];
            foreach($data['data'] as $key => &$val){
                $orderIdAy[] = $val['orderId'];
            }
            $data['data'] = model_dxmOrder::getOrderInfo($orderIdAy);
        }
        $logisticsList = model_dxmOrder::getLogisticsList();
        $trackDogStatus = model_com::getVsConfig('trackDogStatus');
        $usdCurrency = 6.58; //美元兑人民币汇率
        foreach($data['data'] as $key => &$val){
            $orderData = json_decode($val['orderData'], true);
            $profitsData = json_decode($val['profitsData'], true);
            $wishUData = json_decode($val['wishUData'], true);
            $trackData = json_decode($val['trackData'], true);
            $aliData = json_decode($val['aliData'], true);
            $refund = json_decode($val['refund'], true);
            $val += $orderData;
            $val += $profitsData;
            $val += $wishUData;
            $val['logisticsId'] = !empty($logisticsList[$val['logistics']]) ? $logisticsList[$val['logistics']] : '';
            $val['costPriceTotal'] = !empty($val['costPriceTotal']) ? $val['costPriceTotal'] = 'CNY ' . $val['costPriceTotal'] : '-';
            $val['gross'] = !empty($val['gross']) ? 'CNY ' . round($val['gross'], 2) : '-';
            $val['shipFee'] = 0;
            if(!empty($wishUData['payment_requests'])){
                foreach($wishUData['payment_requests'] as $row){
                    if($row['type'] == '退款'){
                        $val['shipFee'] -= $row['amount'];
                    } else {
                        $val['shipFee'] += $row['amount'];
                    }
                }
            }
            $val['shipFee'] = !empty($val['shipFee']) ? 'CNY ' . round($val['shipFee'], 2) : '-';
            $val['priceTotal'] = 0;
            foreach($orderData['productInfo'] as $row){
                $val['currencyShop'] = $row['currency'];
                !empty($row['priceTotal']) && $val['priceTotal'] += $row['priceTotal'];
            }
            $val['currencyShop'] != 'CNY' && $val['rmbPriceTotal'] = 'CNY ' . round($val['priceTotal'] * $usdCurrency, 2);
            $val['platPrice'] = round($val['priceTotal'] * 0.15, 2);
            if(!empty($refund['price'])){
                $refund['currency'] != 'CNY' && $val['rmbRefundPrice'] = 'CNY ' . round($refund['price'] * $usdCurrency, 2);
                $val['refundPrice'] = $refund['price'];
                $val['refundCurrency'] = $refund['currency'];
            }
            $val['currencyShop'] != 'CNY' && $val['rmbPlatPrice'] ='CNY ' . round($val['platPrice'] * $usdCurrency, 2);
            $val['grossMargin'] = !empty($val['grossMargin']) ? $val['grossMargin'] . '%' : '-';
            $val['costMargin'] = !empty($val['costMargin']) ? $val['costMargin'] . '%' : '-';
            //产品信息整理
            $val['_productInfo'] = "<table>";
            foreach($orderData['productInfo'] as $row){
                empty($row['priceTotal']) && $row['priceTotal'] = 0;
                $val['_productInfo'] .= "<tr>
                    <td width='80px'><img style='width: 80px' src='{$row['img']}'></td>
                    <td width='200px'>{$row['sku']} x <span style='color: #FF0000'>{$row['qty']}</span></td>
                    <td width='90px'>{$row['currency']} {$row['priceTotal']}</td>
                </tr>";
            }
            $val['_productInfo'] .= "</table>";
            //物流信息整理
            !empty($trackData['status']) && $val['trackDogStatus'] = !empty($trackDogStatus[$trackData['status']]) ? $trackDogStatus[$trackData['status']] : $trackData['status'];
            !empty($trackData['shippingDay']) && $val['shippingDay'] = $trackData['shippingDay'];
            !empty($trackData['onlineTime']) && $val['onlineTime'] = date('Y-m-d H:i:s', substr($trackData['onlineTime'], 0, -3));
            !empty($trackData['lastTime']) && $val['lastTime'] = date('Y-m-d H:i:s', substr($trackData['lastTime'], 0, -3));
            //采购信息整理
            if(!empty($aliData['baseInfo']['shippingFee'])){
                $val['shippingFee'] = 'CNY ' . $aliData['baseInfo']['shippingFee'];
                $val['cost'] = 'CNY ' . ($aliData['baseInfo']['totalAmount'] - $aliData['baseInfo']['shippingFee']);
            }else{
                $val['shippingFee'] = 'CNY ' . 0;
                $val['cost'] = $val['costPriceTotal'];
            }
            //删除多余数据
            unset($data['data'][$key]['orderData']);
            unset($data['data'][$key]['profitsData']);
            unset($data['data'][$key]['aliData']);
            unset($data['data'][$key]['wishUData']);
            unset($data['data'][$key]['trackData']);
        }
        if(!empty($data['data'][0]) && isset($data['attr']['params'])){
            if(self::$es){
                $sql = model_dxmOrder::searchSqlEs($data['attr']['params'], 'total');
                $total = esSql($sql);
            } else {
                $sql = model_dxmOrder::searchSql($data['attr']['params'], 'total');
                $total = L::sql($sql);
            }
            $totals = [];
            $total[0]['salesPrice'] += $total[0]['freightRevenue'];
            foreach ($total[0] as $k => $v){
                $totals[$k] = round($v, 2);
            }
            $data['data'][0]['sumTotalPrice'] = $totals;
        }
    }

    /**
     * 描述 ：按条件导出数据
     * 作者 ：Zoro.Zhu
    **/
    public function exportCsv(){
        set_time_limit(0);
        $sql = model_dxmOrder::searchSql(array('search' => $_GET));
        $data['data'] = L::sql($sql);
        self::asCall($data);
        of_base_com_csv::download('导出数据' . time());                     //导出数据的文件名
        of_base_com_csv::download(array(
                '店小秘订单号','包裹号','平台','销售店铺','订单状态',
                '最后更新时间','付款时间','标记发货时间','产品信息','国家英文名',
                '收件人','地址1','地址2','城市','州省',
                '邮编','电话','国家中文名','物流渠道','跟踪号',
                '物流商称重(KG)','物流运费','打印面单时间','上网时间','物流最后时间',
                '物流状态','发货天数','1688订单号','快递单号','采购总成本',
                '产品成本','快递费','售价','售价币种','售价RMB',
                '平台佣金','平台佣金RMB','采购总成本（公摊后）','物流运费','毛利',
                '毛利率','成本利润率',
            )
        );
        foreach ($data['data'] as $row){
            of_base_com_csv::download(array(
                    $row['orderId'],$row['parcelNum'],$row['platform'],$row['pAccount'],$row['orderState'],
                    $row['updTime'],$row['paymentTime'],$row['shipTime'],'',$row['countryEn'],
                    $row['contact'],$row['address1'],$row['address2'],$row['city'],$row['province'],
                    $row['zip'],$row['phone'],$row['country'],$row['logistics'],$row['trackNo'],
                    $row['pricing_weight'],$row['shipFee'],$row['printTime'],$row['onlineTime'],$row['lastTime'],
                    $row['trackDogStatus'],$row['shippingDay'],$row['pickingRemark'],$row['singleExpress'],$row['costPriceTotal'],
                    $row['cost'],$row['shippingFee'],$row['priceTotal'],$row['currencyShop'],$row['rmbPriceTotal'],
                    $row['platPrice'],$row['rmbPlatPrice'],$row['costPrice'],$row['shipFee'],$row['gross'],
                    $row['grossMargin'],$row['costMargin'],
                )
            );
        }
    }

    /**
     * 描述 : 修改采购金额和快递单号的页面
     * 作者 : Zoro.Zhu
     */
    public function updPriceView(){
        $orderId = $_GET['orderId'];
        $orderId = trim($orderId, ',');
        !strstr($orderId, ',') && $info = model_dxmOrder::getKeyInfo($orderId);
        $this->view->orderId = $orderId;
        $this->view->singleExpress = !empty($info[0]['singleExpress']) ? $info[0]['singleExpress'] : '';
        $this->view->costPriceTotal = !empty($info[0]['costPriceTotal']) ? $info[0]['costPriceTotal'] : 0;
        $this->view->orderRemark = !empty($info[0]['orderRemark']) ? $info[0]['orderRemark'] : '';
        $this->display('/html/wish/updPrice.html');
    }

    /**
     * 描述 : 修改采购金额和快递单号
     * 作者 : Zoro.Zhu
     */
    public function updPrice(){
        $orderIds = explode(",", $_POST['orderId']);
        foreach($orderIds as $orderId){
            if (empty($orderId)) {
                continue;
            }
            L::sql("UPDATE `dxm_order` 
            SET 
                `singleExpress` = '{$_POST['singleExpress']}',
                `orderRemark` = '{$_POST['orderRemark']}',
                `costPriceTotal` = '{$_POST['costPriceTotal']}'
            WHERE
                `orderId` = '{$orderId}'");
            of_base_com_mq::set(['calProfits', $_POST['orderId']], ['orderId' => $_POST['orderId']]);
        }
        return ['state' => 200, 'info' => '修改成功，系统将会重新计算利润'];
    }

    /**
     * 描述 : 打印
     * 作者 : Zoro.Zhu
     */
    public function printOk(){
        $cookie = model_com::getCookie($_POST['account']);
        $res = serv_rep_dxm::printOk($cookie,$_POST['orderId'], $_POST['logisticsId']);
        if($res){
            //更新订单详情
            $mqRes = ctrl_wish_mq::getOrderDetail(['data'=>['orderId' => $_POST['orderId'],'parcelNum' => $_POST['parcelNum']]]);
            if($mqRes === true){
                //获取面单PDF信息
                $pdfStr = serv_rep_dxm::getLabelInfo($cookie, $_POST['orderId'], $_POST['logisticsId']);
                return ['code' => 200, 'info' => '打印成功'] + $pdfStr;
            }
        }
        return ['code' => 301, 'info' => '打印异常'];
    }

    public function syncEs(){
        set_time_limit(0);
        $class = new serv_rapi_es();
        $re = $class->addIndex('dxm_order');
        p($re);exit;
        $sql = "select * from dxm_order where orderId = '39273803993362110'";
        $data = L::sql($sql);
        foreach($data as $row){
            $row += json_decode($row['orderData'], true);
            $row += json_decode($row['profitsData'], true);
            $trackData = json_decode($row['trackData'], true);
            $row['trackDogStatus'] = !empty($trackData['status']) ? $trackData['status'] : '';
            $row['lastTimeStr'] = !empty($trackData['lastTimeStr']) && strtotime($trackData['lastTimeStr']) !== false ? $trackData['lastTimeStr'] : '2000-01-01 00:00:00';
            $row['paymentTime'] = !empty($row['paymentTime']) && strtotime($row['paymentTime']) !== false ? $row['paymentTime'] : '2000-01-01 00:00:00';
            $row['printTime'] = !empty($row['printTime']) && strtotime($row['printTime']) !== false ? $row['printTime'] : '2000-01-01 00:00:00';

            $row['sku'] = ',';
            foreach($row['productInfo'] as $r){
                $row['sku'] .= $r['sku'] . ',';
            }
            unset($row['orderData']);
            unset($row['wishUData']);
            unset($row['aliData']);
            unset($row['profitsData']);
            unset($row['trackData']);
            unset($row['productInfo']);
//            p($row);exit;
//            $class->delete('vs', $row['orderId']);
//            p($row);exit;
            p($row);
            echo $row['orderId'] . '<br>';
            $res = $class->insert('dxm_order', $row['orderId'], $row);
            p($res);
        }
    }

    public function test(){
//        $sql = "SELECT orderId,orderState FROM vs WHERE  dxmAccount IN ('zorozhu','zqin','zoro_zhu') AND orderState != '已作废' order by orderState";

        $sql = "SELECT
             count(orderId)
        FROM
            dxm_order
        WHERE dxmAccount IN ('zorozhu','zqin','zoro_zhu') AND orderState != '已作废'";
        $data = esSql($sql);
        p($data);
    }

}
return true;